from supabase import create_client, Client
import sys
import os
import magic


# 替换为你的项目信息
bucketName = sys.argv[5]
SUPABASE_URL = sys.argv[6] # "https://shncgsmugxjijgarupbd.supabase.co"
SUPABASE_KEY = sys.argv[7] # "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNobmNnc211Z3hqaWpnYXJ1cGJkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ0NTc3ODIsImV4cCI6MjA3MDAzMzc4Mn0.d5Y_kMzxNX0OSH2K0mzxqNoVQDfrJbvyavXrBs15BI4"

# 初始化客户端
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)



def upload_file(local_file_path, storage_path, overwrite):
	# # 本地文件路径
	# local_file_path = "./test.txt"
	# # 存储桶中的目标路径（如 my-bucket 下的 files/test.txt）
	# storage_path = "files/test.txt"
	try:

		# print(local_file_path)
		# print(storage_path)
		# 打开文件并上传
		with open(local_file_path, "rb") as f:
			magic_desc = magic.Magic()
			file_content = f.read(1024)  # 读取前1024字节足够识别类型
			content_desc = magic_desc.from_buffer(file_content)
			print(f"通过二进制内容识别: {content_desc}")


			file_options = {"upsert":str(overwrite).lower()}
			a = "binary/octet-stream"
			if "ASCII text" in content_desc:
				a = None

			if a != None:
				file_options["Content-Type"] = a

			response = supabase.storage.from_(bucketName).upload(storage_path, f, file_options = file_options)

		if response:
			print("上传成功", response)

		return True

	except Exception as e:
		print("上传失败：", str(e))

		return False


# upload_file()

def download_file(storage_path, local_save_path, overwrite):
	# # # 存储桶中的文件路径
	# storage_path = "files/test2.txt"
	# # # 本地保存路径
	# local_save_path = "./downloaded_test.txt"
	if not overwrite:
		if os.path.exists(local_save_path):
			print("下载失败：本地文件已存在", local_save_path)
			return False


	try:
		# 下载文件
		response = supabase.storage.from_(bucketName).download(storage_path)
		
		if isinstance(response, bytes):
			# 保存到本地
			with open(local_save_path, "wb") as f:
				f.write(response)
			print("下载成功，保存到：", local_save_path)
			return True
		else:
			print("下载失败：", response.error)
			return False
	except Exception as e:
		print("下载失败：", str(e))
		return False


# download_file()


def str_to_bool(s):
    # 先转换为小写，兼容大小写不同的情况（如"False"、"TRUE"）
    s_lower = s.lower()
    if s_lower == "true":
        return True
    elif s_lower == "false":
        return False
    else:
        # 处理无效输入
        raise ValueError(f"无法将字符串 '{s}' 转换为布尔值，有效值为 'true' 或 'false'")

overwrite = str_to_bool(sys.argv[4])

if str_to_bool(sys.argv[1]):
	exit(upload_file(sys.argv[2], sys.argv[3], overwrite) == 0 and True or False)
else:
	exit(download_file(sys.argv[2], sys.argv[3], overwrite) == 0 and True or False)


